import React, { Component, useState } from "react";
import { createStore } from "redux";
/* 
  1.定义reducer函数
  //作用：根据不同的action对象，返回不同的新的state
  //state:管理的数据初始状态
  //action:对象type标记当前想要什么样的修改
*/
function reducer(state = { count: 0 }, action) {
  if (action.type === "INCREMENT") {
    return { count: state.count + 1 };
  }
  if (action.type === "DECREMENT") {
    return { count: state.count - 1 };
  }
  return state;
}
/* 
  2.使用reducer函数生成store实例
  */
const store = createStore(reducer);
/* 
  3.通过store实例的subscribe订阅数据变化
   回调函数可以在每次state发生变化的时候自动执行
 */
store.subscribe(() => {
  console.log(store.getState(), "state变化了");
});
/* 
4.通过store实例的dispath函数提交action更改状态
*/
const inBtn = document.getElementById("increment");
// inBtn.addEventListener("click", () => {
//   //增
//   store.dispatch({
//     type: "INCREMENT",
//   });
// });
/* 
  5.通过store实例的getState方法获取最新状态更新到视图中
*/
export default function URedux() {
  let handle = () => {
    store.dispatch({ type: "INCREMENT" });
  };
  let [num, setNum] = useState(0);
  store.subscribe(() => {
    console.log('值变化了');
    setNum(store.getState().count);
  });
  return (
    <>
      <h1>Redux的学习</h1>
      {num}
      <button onClick={handle}>修改值</button>
    </>
  );
}
